from machine import Pin, PWM
import time

# 定义音调频率
tones = {
    '1-': 262,
    '2-': 294,
    '3-': 330,
    '4-': 349,
    '5-': 392,
    '6-': 440,
    '7-': 494,
    '1=': 523,
    '2=': 587,
    '3=': 659,
    '4=': 698,
    '5=': 784,
    '6=': 880,
    '7=': 988,
    '1+': 1046,
    '2+': 1175,
    '3+': 1318,
    '4+': 1397,
    '5+': 1568,
    '6+': 1760,
    '7+': 1976,
    '__': 0
}

beeper = PWM(Pin(2, Pin.OUT), freq=1000, duty=0)

def play(beeper, melody, duty = 10):
    i = 0
    keep = False
    while i  < len(melody):
        if melody[i] == '(':
            i += 1
            keep = True
            continue
        elif melody[i] == ')':
            i += 1
            keep = False

            # 连音结束后稍微停顿下
            beeper.duty(0)
            time.sleep_ms(50)
            continue

        tone, level = melody[i], melody[i+1]
        i += 2
        freq = tones[tone+level]
        if freq:
            beeper.init(duty=duty, freq=freq)
        else:
            beeper.duty(0)  # 空拍时静音

        # 停顿一下 （四四拍每秒两个音，每个音节中间稍微停顿一下）
        time.sleep_ms(200)
        if not keep:
            print(tone, level)
            beeper.duty(0)  # 设备占空比为0，即不上电
        time.sleep_ms(50)

# 《路在何方》
melody = \
"(6-1=1=6-)(3=3=3=)2=(2=1=1=1=1=1=1=1=)(7-6-6-7-)(2=2=2=)3=(1=6-6-6-6-6-6-6-)" \
"(3=3=3=3=)(6=6=6=3=)(6=6=5=4=)(3=3=3=3=)(1=1=1=)2=(3=3=4=3=)(2=2=2=2=2=2=2=2=)" \
"(6-6-)(3=3=)(2=3=6-6-)(1=1=1=1=1=1=3=3=)(2=7-7-3=)(2=6-1=2=)(3=3=3=3=3=3=3=3=)" \
"(3=3=3=3=)(6=6=6=3=)(6=6=5=4=)(3=3=3=3=)(5=2=2=4=)(3=2=1=1=)(2=2=2=2=2=2=3=3=)" \
"(2=7-7-3=)(7-6-5-5-)(6-6-6-6-6-6-)(3=3=)(5=5=5=5=5=5=)(3=5=)(6=6=6=)1+(7=6=)(5=5=)" \
"(6=6=6=6=6=6=6=6=)(1+1+1+1+)(7=7=7=)6-(5=6=)(5=5=5=5=)(5=6=)(3=3=3=3=3=3=3=3=)" \
"(1+1+1+1+)(7=7=7=)6=(5=6=)(5=5=5=5=)(5=6=)(3=3=3=3=3=3=3=3=)(5-6-)1=(3=3=3=)1=" \
"(2=3=)(2=2=2=2=2=2=)(2=7-7-)3=(7-6-5-5-)(6-6-6-6-6-6-6-6-)(5-6-6-)1=(3=3=3=)1=" \
"(2=3=)(2=2=2=2=2=2=)(3=3=5=5=5=5=)(3=3=)(7=7=7=1+7=6=5=5=)(6=6=6=6=6=6=6=6=6=6=6=6=6=6=6=6=)" \
"(3=3=5=5=5=5=)(3=3=)(7=7=7=1+7=6=5=5=)(6=6=6=6=6=6=6=6=6=6=6=6=6=6=6=6=)"

play(beeper, melody)

# 《小星星》
# melody = "1=1=5=5=6=6=5=__4=4=3=3=2=2=1=__5=5=4=4=3=3=2=__5=5=4=4=3=3=2=__1=1=5=5=6=6=5=__4=4=3=3=2=2=1="
# play(beeper, melody)

beeper.deinit()

